package com.huawei.mptcp.testapp;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.mptcptestapp.R;
import com.huawei.mptcp.upload.UploadDownLoadMachine;
import com.huawei.mptcp.utils.GlobalConfig;
import com.huawei.mptcp.utils.ILogUtil;
import com.huawei.wireless.ConnectionChangeReceiver;

import android.app.Activity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MptcpMainActivity extends Activity {
	private static final String TAG = "MptcpTestActivity";
	
//	private AlarmInforStrObserver alarmObserver = null;
	
	private static TextView tv = null;
	
	private static Handler handler=new Handler(); 
	
	
//	public static String alarmInforStr = "";
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		IntentFilter filter = new IntentFilter();  
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
		ConnectionChangeReceiver cr = new com.huawei.wireless.ConnectionChangeReceiver();
		registerReceiver(cr, filter); 
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mptcp_main);
		
		
		tv = (TextView) findViewById(R.id.alarmInforStrID);
		ILogUtil.d(TAG, "begin click button");
		
		tv.setMovementMethod(new ScrollingMovementMethod());

		final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroupTestMode);
		
		getUserTcpServerIpAndPortSetting();
		
		final Button interflowTestBt  = (Button) findViewById(R.id.mptcpTestId);
		interflowTestBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				String btText = interflowTestBt.getText().toString();
				if(btText.equals(getApplicationContext().getString(R.string.begainButton))){
					dealWithRadioButtonAndSetTestMode(radioGroup);
					cleanCsvTestDataFile();
					getUserTcpServerIpAndPortSetting();
					
					interflowTestBt.setText(getApplicationContext().getString(R.string.stopButton));
					interflowTestBt.setBackgroundResource(R.drawable.red_button);
					
					MptcpMainActivity.updateAlarmInfor("success:test...");
					MptcpMainActivity.updateAlarmInfor("success:test data in "+GlobalConfig.storeDir);
					
					new UploadDownLoadMachine().start();
					ConnectionChangeReceiver.isStart = true;
				}else{			
					interflowTestBt.setText(getApplicationContext().getString(R.string.begainButton));
					interflowTestBt.setBackgroundResource(R.drawable.blue_button);
		
				}
			}
		});
		
	
		//clear log
		final Button clearLogBt  = (Button) findViewById(R.id.clearLogButtonId);
		clearLogBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cleanCsvTestDataFile();
			}
		});
		
		
		//radion button ,select the test mode ,include uplink throughput, downlink throughput, and rtt test mode
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
			     @Override 
			     public void onCheckedChanged(RadioGroup group, int checkedId) { 
			    	 dealWithRadioButtonAndSetTestMode(radioGroup);
			     }
	     });
		 
	
	}

	/**
	 * clean csv test file
	 */
	public void cleanCsvTestDataFile(){
		ILogUtil.d(TAG, "clear all logs and delete csv file");
		tv.setText(Html.fromHtml("clear log success"));
		try {

			File realFile = new File(GlobalConfig.storeDir);
			File[] allFiles = realFile.listFiles();
			for(File temp:allFiles){
				if(temp.getName().endsWith(".csv")){
					ILogUtil.d(TAG, "shold deleted:"+temp.getName());
					boolean isOk = new File(realFile,temp.getName()).delete();
					if(isOk){
						ILogUtil.d(TAG, "deleted:"+temp.getName()+" success");
					}
				}
			}

			
			
		} catch (Exception e) {
			ILogUtil.exception(TAG, e);
			updateAlarmInfor("failed:clear log and delete csv file failed");
		}
		updateAlarmInfor("success:clear log and delete csv file success");
	}
	
	
	
	/**
	 * public funtion set test mode include uplink ,downlink ,rtt
	 */
	public void dealWithRadioButtonAndSetTestMode( RadioGroup radioGroup){
		RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
	    int buttonId = radioButton.getId();
	    switch(buttonId){
	    	case R.id.radioUplink:
	    		updateAlarmInfor("success:you chosed uplink throughput test");
	    		UploadDownLoadMachine.setTestMode(0);
	    		break;
	    	case R.id.radioDownlink:
	    		updateAlarmInfor("success:you chosed downlink throughput test");
	    		UploadDownLoadMachine.setTestMode(1);
	    		break;
	    	case R.id.radioRttTest:
	    		updateAlarmInfor("success:you chosed rtt test");
	    		UploadDownLoadMachine.setTestMode(2);
	    		break;
	    	default:
	    		updateAlarmInfor("failed:you chosed radio buttion id not matched");
	    		break;
	    }
	}
	
	/**
	 * get the ui user settings of server ip and server port
	 */
	public void getUserTcpServerIpAndPortSetting(){
		EditText serverIpAndPortSettings  = (EditText) findViewById(R.id.tcpServerIpPort);
		String userSettingsText = serverIpAndPortSettings.getText().toString();
		String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}:\\d{0,5}"; 
		Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(userSettingsText);
        if(!matcher.matches()){
        	updateAlarmInfor("failed: serverIp:serverPort format error,please edit like 127.0.0.1:80 ");
        	return;
        }
        String[] serverSettings = userSettingsText.split(":");
        GlobalConfig.setServerIp(serverSettings[0].trim());
        try{
        	GlobalConfig.setServerPort(Integer.parseInt(serverSettings[1].trim()));
        }catch(Exception e){
        	updateAlarmInfor("failed: serverPort format error,please use int number ");
        }
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mptcp_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


    
    public synchronized static void updateAlarmInfor(final String str) {

		handler.post(new  Runnable(){  
	        @Override  
	        public void run() {  
	        	String existAlarmInforStr = Html.toHtml(tv.getEditableText());
	        	if(str.startsWith("success:")) {
	        		existAlarmInforStr+= "<font color = '#308A24'>"+str+"</font><br>";
	        	}
	        	if(str.startsWith("failed:")) {
	        		existAlarmInforStr += "<font color = '#ff0000'>"+str+"</font><br>";
	        	}
	        	tv.setText(Html.fromHtml(existAlarmInforStr));
	        }     
	    });
    }
    
}
